using System.Collections;
using System.Collections.Generic;
using UnityEngine;


namespace RuntimeDebugger
{
	public class FPSProfilerBehaviour : MonoBehaviour
	{
		private float m_lastAvgTime;
		private int m_avgFPSCount;
		private float m_lastFrameTime;

		private const double AVGCountTime = 1.0f;

		public FPSProfiler FPS { get; private set; }


		private void Awake()
		{
			FPS = new FPSProfiler();
			ResetData();
		}

		public void ResetData()
		{
			m_lastAvgTime = Time.realtimeSinceStartup;
			m_lastFrameTime = Time.realtimeSinceStartup;
			m_avgFPSCount = 0;

			FPS?.ResetData();
		}

		private void Update()
		{
			if (null == FPS)
			{
				return;
			}

			FPS.FrameCount = Time.frameCount;
			FPS.Realtime = Time.realtimeSinceStartup;
			float realtimeNow = FPS.Realtime;
			float frameTime = realtimeNow - m_lastFrameTime;
			if (frameTime > 0)
			{
				FPS.FrameTime = (int)(frameTime * 1000);
				FPS.FPS = 1.0f / frameTime;
				m_lastFrameTime = realtimeNow;
			}

			m_avgFPSCount++;
			float avgTime = realtimeNow - m_lastAvgTime;
			FPS.AvgFPSMin = FPS.AvgFPSMin < 0 ? FPS.FPS : Mathf.Min(FPS.AvgFPSMin, FPS.FPS);
			FPS.AvgFPSMax = FPS.AvgFPSMax < 0 ? FPS.FPS : Mathf.Max(FPS.AvgFPSMax, FPS.FPS);
			if (avgTime > AVGCountTime)
			{
				FPS.AvgFPS = m_avgFPSCount / avgTime;

				m_avgFPSCount = 0;
				FPS.AvgFPSMin = -1.0f;
				FPS.AvgFPSMax = -1.0f;
				m_lastAvgTime = realtimeNow;
			}
		}
	}

	public class FPSProfiler
	{
		public int FrameCount { get; set; }
		public float Realtime { get; set; }
		public float FPS { get; set; }
		public int FrameTime { get; set; }
		public float AvgFPS { get; set; }
		public float AvgFPSMin { get; set; }
		public float AvgFPSMax { get; set; }

		public void ResetData()
		{
			AvgFPSMin = -1.0f;
			AvgFPSMax = -1.0f;

			FrameCount = 0;
			Realtime = 0;
			FPS = 0;
			FrameTime = 0;
			AvgFPS = 0;
		}
	}
}